import React, { useCallback } from 'react';
import { Box } from '@mui/material';
import {
  ReactFlow,
  MiniMap,
  Controls,
  Background,
  BackgroundVariant,
  type Connection,
  type Edge,
  type Node,
} from '@xyflow/react';
import { useFlowStore } from '../../store/flowStore';
import { nodeTypes } from '../nodes/nodeTypes';
import { isValidConnection as validateConnection } from '../../utils/connectionValidator';
import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts';
import type { NodeData } from '../../types/behaviorTree';

/**
 * React Flow 画布组件
 * 负责渲染行为树编辑器的画布和交互
 */
export const FlowCanvas: React.FC = () => {
  const {
    nodes,
    edges,
    onNodesChange,
    onEdgesChange,
    onConnect,
    setSelectedNodeId,
  } = useFlowStore();

  const { handleKeyDown } = useKeyboardShortcuts();

  /**
   * 处理节点点击事件
   */
  const onNodeClick = useCallback(
    (_event: React.MouseEvent, node: Node<NodeData>) => {
      setSelectedNodeId(node.id);
    },
    [setSelectedNodeId]
  );

  /**
   * 处理画布点击事件
   */
  const onPaneClick = useCallback(() => {
    setSelectedNodeId(null);
  }, [setSelectedNodeId]);

  /**
   * 验证节点连接是否符合行为树规则
   */
  const isValidConnection = useCallback(
    (connection: Connection | Edge) => {
      // 将 Edge 转换为 Connection 格式
      const conn: Connection = {
        source: connection.source,
        target: connection.target,
        sourceHandle: connection.sourceHandle ?? null,
        targetHandle: connection.targetHandle ?? null,
      };
      const result = validateConnection(conn, nodes, edges);
      if (!result.valid && result.reason) {
        console.warn(`Invalid connection: ${result.reason}`);
      }
      return result.valid;
    },
    [nodes, edges]
  );

  return (
    <Box
      component="main"
      sx={{
        flexGrow: 1,
        p: 0,
        display: 'flex',
        flexDirection: 'column',
        height: 'calc(100vh - 64px)',
      }}
      tabIndex={0} // 使 Box 可聚焦，以便监听键盘事件
      onKeyDown={handleKeyDown} // 添加键盘事件监听
    >
      <ReactFlow
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        nodeTypes={nodeTypes}
        fitView // 自动调整视图以适应所有节点
        style={{ flexGrow: 1 }} // 使画布占据可用空间
        isValidConnection={isValidConnection} // 验证连接的有效性
        onNodeClick={onNodeClick} // 节点点击事件
        onPaneClick={onPaneClick} // 画布点击事件
      >
        {/* 迷你地图 */}
        <MiniMap />
        {/* 控制器（缩放、定位） */}
        <Controls />
        {/* 背景网格 */}
        <Background variant={BackgroundVariant.Dots} gap={12} size={1} />
      </ReactFlow>
    </Box>
  );
};

